package com.xiaozhameng.bootstudy.all.txtest;


import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaozhameng.bootstudy.dao.UserDao;
import com.xiaozhameng.bootstudy.entity.UserEntity;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service("txUserService")
public class TxUserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements IService<UserEntity> {

    @Autowired
    private TxUserServiceAAImpl txUserServiceAA;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void methodTx(){
        // 保存一个方法
        txUserServiceAA.methodAA();
    }


    public void methodA(){
        // 保存一个方法
        this.save(this.buildUser("AA1"));
        TxUserServiceImpl service = (TxUserServiceImpl) AopContext.currentProxy();
        service.methodB();
        this.save(this.buildUser("AA2"));
    }

    @Transactional(rollbackFor = Exception.class)
    public void methodB(){
        // 保存一个方法
        this.save(this.buildUser("BB1"));
        int i = 10 / 0;
        this.save(this.buildUser("BB2"));
    }


    /**
     * 构建一个user 对象
     */
    private UserEntity buildUser(String userName){
        UserEntity entity = new UserEntity();
        entity.setName(userName);
        entity.setAddress("北京测试");
        entity.setBirthday(new Date());

        return entity ;
    }

}